<?php

inc_class("pcre");

$delta = 128;

$keys = array ( 255, 255-$delta );
$array = array ( 255 => 1 );

$sess_file_name = "session.txt";

if (empty($_REQUEST["erase"])) {
    $content = file_get_contents($sess_file_name);
    if (strlen($content)) {
        $array = unserialize($content);
    }
    if (count($array)<=256/$delta+1) {
        $array[intval("".(array_sum($_REQUEST["cl"])/count($_REQUEST["cl"]))."")] = $_REQUEST["result"]/255;
        $tmp = max($_REQUEST["cl"]) - $delta;
        $keys = array ( $tmp, ($tmp-$delta) < 0 ? 0 : $tmp-$delta );
    }
}
if (!empty($_REQUEST["env"])) {
    die("<pre>".htmlentities(print_r($_ENV, 1)).htmlentities(print_r($_REQUEST, 1))."</pre>");
}

unset($array[0]);
$array[0] = 0;
$sess = fopen($sess_file_name, "w+t");
fwrite($sess, serialize($array));
fclose($sess);

if (!empty($_REQUEST["erase"])) {
    $array = array ( 0 => 0, 255 => 1 );
    $sess = fopen($sess_file_name, "w+t");
    fclose($sess);
}

draw($array, $keys);

function draw($array, $keys)
{
    $out = "<message proccess=\"replace\" recepient=\"table\">";
    $out .= '<img id="table" name="table" src="http://localhost/gamma.png?time='.time().'" width="256" height="256" title="Correctly gamma" alt="Curve: &quot;Correctly gamma&quot;" />';
    $out .= "</message>";
    $out .= "<message proccess=\"colors\" recepient=\"table\"><colors>";
    foreach ( $keys as $color ) {
        $out .= "<color>{$color}</color>";
    }
    $out .= "</colors></message>";



    $image_type = IMAGETYPE_PNG;
    $extension = image_type_to_extension($image_type);
    $mime = image_type_to_mime_type($image_type);
    $im = @imagecreate(256, 256) or die("Cannot Initialize new GD image stream");
    $red = imagecolorallocate($im, 194, 0, 0);
    $green = imagecolorallocate($im, 0, 194, 0);
    $blue = imagecolorallocate($im, 0, 0, 194);
    $black = imagecolorallocate($im, 0, 0, 0);
    $bg = imagecolorallocate($im, 226, 226, 226);
    imagefill($im, 0, 0, $bg);
    $count = 0;
    reset($array);
    list($x0, $y0) = each($array);
    foreach ( $array as $x => $y ) {
        if ($count++) {
            imageline($im, $x0, 255 - $y0*255, $x, 255 - $y*255, $black);
            $x0 = $x;
            $y0 = $y;
        }
    }
    /*header("Content-type: " . image_type_to_mime_type($image_type));
    header('Content-Disposition: attachment; filename="bg-sample'.$extension.'"');*/
    ob_start();
    imagepng($im);
    $img_fname = "gamma".$extension;
    $img = fopen($img_fname, "w");
    fwrite($img, ob_get_contents());
    fclose($img);
    ob_end_clean();
    imagedestroy($im);
    filedump('<?xml version="1.0" encoding="Windows-1251" ?><response>'.$out.'</response>');
}


?>